#ifndef COMPOSER_H
#define COMPOSER_H

#include <vector>
#include <QPainter>
#include "asynclayer.h"

#define COMPOSER Composer::getInstance()

/*
 * 图层融合器
 */
class Composer
{
public:
    // 获取单例实体
    static Composer* getInstance()
    {
        static Composer instance;
        return &instance;
    }

    // 禁止复制 & 赋值
    Composer(const Composer& other) = delete;
    Composer& operator=(const Composer& other) = delete;

    // 添加图层
    void insert(std::shared_ptr<AsyncLayer> layer)
    {
        _layers.push_back(layer);
    }

    // 更新所有图层
    void update(int width, int height)
    {
        for (auto layer : _layers)
        {
            // 非空
            if (layer)
            {
                layer->step(width, height);
            }
        }
    }

    // 获取融合图层
    void compose(QPixmap& stacked)
    {
        // 融合所有图层
        QPainter painter(&stacked);

        for (const auto& layer : _layers)
        {
            if (layer)
            {
                if (layer->isAsync())
                {
                    std::unique_lock<std::mutex> lock(layer->_pix_mutex);
                    painter.drawPixmap(0, 0, layer->_pixmap);
                }
                else
                {
                    painter.drawPixmap(0, 0, layer->_pixmap);
                }
            }
        }
    }

private:
    // 禁用共有构造 & 析构
    Composer() {}
    ~Composer() {}

    // 管理所有图层
    std::vector<std::shared_ptr<AsyncLayer> > _layers;
};

#endif // COMPOSER_H
